import { Module } from 'vuex'
import http from '../common/request'
import { groupApi } from '../api/group'

interface IGroup {
  aliasName: string
  headImage: string
  headImageThumb: string
  id: number
  name: string
  notice: string
  ownerId: number
  remark: string
}

export interface IGroupState {
  groups: IGroup[]
  activeIndex: number
}

const groupStore: Module<IGroupState, any> = {
  state: {
    groups: [],
    activeIndex: -1
  },
  mutations: {
    setGroups(state, groups) {
      state.groups = groups
    },
    activeGroup(state, index) {
      state.activeIndex = index
    },
    addGroup(state, group) {
      state.groups.unshift(group)
    },
    removeGroup(state, groupId: number) {
      state.groups.forEach((g, index) => {
        if (g.id == groupId) {
          state.groups.splice(index, 1)
          if (state.activeIndex >= state.groups.length) {
            state.activeIndex = state.groups.length - 1
          }
        }
      })
    },
    updateGroup(state, group) {
      state.groups.forEach((g, idx) => {
        if (g.id == group.id) {
          // 拷贝属性
          Object.assign(state.groups[idx], group)
        }
      })
    },
    clear(state) {
      state.groups = []
      state.activeIndex = -1
    }
  },
  actions: {
    loadGroup(context) {
      return new Promise((resolve, reject) => {
        groupApi.getGroupList().then((groups) => {
          context.commit('setGroups', groups)
          resolve(groups)
        })
          .catch((res) => {
            reject(res)
          })
      })
    }
  }
}

export default groupStore
